<?php
class Comment_Manager extends Model {
	private $_current_blogger_id;
	private $_current_entry_id;
	
	function Comment_Manager() {
		parent::Model();
		$this->_current_blogger_id = 0;
		$this->_current_entry_id = 0;
	}
	
	function SetCurrentBloggerID($current_blogger_id) {
		$this->_current_blogger_id = $current_blogger_id;
	}
	
	function SetCurrentEntryID($current_entry_id) {
		$this->_current_entry_id = $current_entry_id;
	}
	
	function AddComment($comment) {
		if(!is_array($comment)) {
			throw new Exception('Invalid comment data!');
		}
		
		$parms = array(
			'entry_id' => $comment['entry_id'],
			'author_name' => $comment['author_name'],
			'email' => $comment['email'],
			'post_time' => $comment['post_time'],
			'ip' => $comment['ip'],
			'url' => $comment['url'],
			'state' => $comment['state'],
			'by_blogger_id' => $comment['by_blogger_id']
		);
		$this->db->insert('nt_comments', $parms);
		$new_comment_id = $this->db->insert_id();
		
		$parms1 = array(
			'comment_id' => $new_comment_id,
			'content' => $comment['content']
		);
		$this->db->insert('nt_comment_data', $parms1);
		
		if($comment['state'] == 1) {
			$this->db->query('UPDATE `nt_entries` SET `comment_num` = `comment_num` + 1 WHERE `id` = ?', array($comment['entry_id']));
		}
		
		return $new_comment_id;
	}
	
	function CheckSpam($comment) {
		$parms = array(
			'key' => '9f87bfa4c12a', // from my wordpress.com account
			'home' => 'http://blog.sinzy.net/',
			'ua' => $comment['user_agent']
		);
		$this->load->library('microakismet', $parms);
		$vars = array(
			'blog' => 'http://blog.sinzy.net/',
			'user_ip' => $comment['ip'],
			'user_agent' => $comment['user_agent'],
			'referrer' => $comment['referrer'],
			'permalink' => $comment['permalink'],
			'comment_type' => 'comment',
			'comment_author' => $comment['author_name'],
			'comment_author_email' => $comment['email'],
			'comment_author_url' => $comment['url'],
			'comment_content' => $comment['content']
		);
		
		return $this->microakismet->check($vars);
	}
	
	function DeleteComment($comment_id) {
		// check if has right
		$test = $this->db->query('SELECT `blogger_id` FROM `nt_entries` WHERE `id` = (SELECT `entry_id` FROM `nt_comments` WHERE `id` = ? AND `entry_id` = ?)', array($comment_id, $this->_current_entry_id));
		$tr = TRUE;
		if($test->num_rows() == 0) {
			$tr = FALSE;
		} elseif($test->row()->blogger_id != $this->_current_blogger_id) {
			$tr = FALSE;
		}
		if(!$tr) {
			throw new Exception("Not permitted to delete this comment!");
		}
		
		$this->db->query('DELETE FROM `nt_comment_data` WHERE `comment_id` = ?', array($comment_id));
		$this->db->query('DELETE FROM `nt_comments` WHERE `id` = ? AND `entry_id` = ?', array($comment_id, $this->_current_entry_id));
		if($this->db->affected_rows() > 0) {
			$this->db->query('UPDATE `nt_entries` SET `comment_num` = `comment_num` - 1 WHERE `id` = ?', array($this->_current_entry_id));
		}
	}
}
?>